package com.hae.shop.micoshopportalpayweb.controller;

import com.hae.shop.common.base.Response;
import com.hae.shop.common.constant.Constants;
import com.hae.shop.micoshopportalpayweb.controller.feign.PayFeign;
import com.hae.shop.pay.model.reqDto.PayReqDto;
import com.hae.shop.pay.model.respDto.PayOrgRespDto;
import com.hae.shop.pay.model.respDto.PayTransactionRespDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.constraints.NotBlank;
import java.util.List;

@Controller
@Validated
public class PayController {

    @Autowired
    private PayFeign payFeign;

    @RequestMapping("/")
    public String indexHtml() {

        return "index";
    }

    @RequestMapping("/pay")
    public String pay(@RequestParam("payoken") @NotBlank String payoken, Model model) {
        //调用支付服务查询支付信息
        Response<PayTransactionRespDto> transactionRespDtoResponse = payFeign.getPayTransactionByToken(payoken);
        if (!transactionRespDtoResponse.isSuccess()) {
            model.addAttribute("error", transactionRespDtoResponse.getErrorMsg());
            return Constants.ERROR_FTL;
        }
        //调用支付服务查询支付机构
        Response<List<PayOrgRespDto>> orgRespDtoResponse = payFeign.getPayOrg();
        if (!orgRespDtoResponse.isSuccess()) {
            model.addAttribute("error", orgRespDtoResponse.getErrorMsg());
            return Constants.ERROR_FTL;
        }
        //将信息加载到页面model
        model.addAttribute("data", transactionRespDtoResponse.getResult());
        model.addAttribute("paymentChanneList", orgRespDtoResponse.getResult());
        return "pay";
    }

    @RequestMapping("/paySure")
    public String paySure(@RequestParam("payoken") @NotBlank String payoken,
                          @RequestParam("payoken") @NotBlank String payOrgId, Model model) {
        PayReqDto payReqDto = new PayReqDto();
        payReqDto.setPayoken(payoken);
        payReqDto.setPayOrgId(payOrgId);
        Response<Boolean> payResult = payFeign.payOrder(payReqDto);
        if (!payResult.isSuccess()) {
            return Constants.ERROR_FTL;
        }
        return "pay-success";
    }
}
